package main

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"
	"net/http"
	"strconv"
	_ "github.com/go-sql-driver/mysql"
)

func main() {
	
	mux := http.NewServeMux()
    // 应用中间件到所有路由
    handler := corsMiddleware(mux)
	// dynamic functions
	mux.HandleFunc("/register", register)//注册
	mux.HandleFunc("/login", login)//用户登录
	mux.HandleFunc("/meal-requests", meal_request)//需求获取
	mux.HandleFunc("/meal-services", meal_service)//服务获取
	mux.HandleFunc("/confirmorder", confirm_order)//确认订单
	mux.HandleFunc("/requestpublish", request_publish)//需求发布
	mux.HandleFunc("/servicepublish", service_publish)//服务发布
	mux.HandleFunc("/getRequestOrders", getRequestOrders)//获取用户需求订单
	mux.HandleFunc("/getServiceOrders", getServiceOrders)//获取用户服务订单
	mux.HandleFunc("/ordercomplaint", order_complaint)//投诉
	mux.HandleFunc("/stuinfo", stu_info)//个人信息修改
	mux.HandleFunc("/adminlogin", admin_login)//管理员登录
	mux.HandleFunc("/getComplaints", get_complaints)//查看投诉
	mux.HandleFunc("/deal-complaint", deal_complaint)//处理投诉
	mux.HandleFunc("/pull-black", pull_black)//拉黑
	// static handlers
	mux.Handle("/", http.FileServer(http.Dir("C:/Users/86135/Desktop/学习/数据库实验")))
	mux.Handle("/src", http.FileServer(http.Dir("C:/Users/86135/Desktop/学习/数据库实验/src")))
	mux.Handle("/src/components", http.FileServer(http.Dir("C:/Users/86135/Desktop/学习/数据库实验/src/components")))
	mux.Handle("/src/router", http.FileServer(http.Dir("C:/Users/86135/Desktop/学习/数据库实验/src/router")))
	// listen ports
	log.Fatal(http.ListenAndServe(":8080", handler))

}

func Connection() (*sql.DB, error) {
	db, err := sql.Open("mysql", "root:@tcp(127.0.0.1:3306)/test")
	if err != nil {
		return nil, err
	}
	return db, nil
}


func corsMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Access-Control-Allow-Origin", "*") // 允许所有域名访问，也可以指定具体的域名
        w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
        if r.Method == "OPTIONS" {
            w.WriteHeader(http.StatusOK)
            return
        }
        next.ServeHTTP(w, r)
    })
}

func register(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err!= nil {
		fmt.Println(err)
		return
	}
	defer db.Close()
	// get form data
	card,_ := strconv.Atoi(r.FormValue("card"))
	password:= r.FormValue("password")
	// check if name already exists
	response:= make(map[string]bool)
	_,err = db.Exec("INSERT INTO user (card,password,type) VALUES (?,?,1)", card, password)
	if err!= nil {
		fmt.Println(err)
		fmt.Println("该卡号已被注册或者不存在在学生表中")
		response["success"] = false
		return
	}else{
		response["success"] = true
		responseJSON, err := json.Marshal(response)
    	if err != nil {
        	http.Error(w, err.Error(), http.StatusInternalServerError)
        	return
    	}
		// 设置Content-Type为application/json，并返回响应
		w.Header().Set("Content-Type", "application/json")
		w.Write(responseJSON)
	}
}

func login(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	card,_ := strconv.Atoi(r.FormValue("card"))
	password := r.FormValue("password")
	var count int
	var Type int
	response := make(map[string]bool)
	err = db.QueryRow("SELECT count(ID) FROM user WHERE card = ? and password = ?", card, password).Scan(&count)
	if err != nil {
		fmt.Println(err)
		return
	}else{
		if(count > 0){
			err = db.QueryRow("SELECT type FROM user WHERE card = ? and password = ?", card, password).Scan(&Type)
			if err != nil {
				fmt.Println(err)
				return
			}
			if(Type == 1){
				fmt.Println("登录成功")
			    response["success"] = true
			}else{
				fmt.Println("该卡号已被拉黑")
				response["success"] = false
				response["black"] = true
			}
		}else{
			fmt.Println("卡号或密码错误")
			response["success"] = false
		}
		responseJSON, err := json.Marshal(response)
    	if err != nil {
        	http.Error(w, err.Error(), http.StatusInternalServerError)
        	return
    	}
		// 设置Content-Type为application/json，并返回响应
		w.Header().Set("Content-Type", "application/json")
		w.Write(responseJSON)
	}
}

type MealRequest struct {
	DemandID       int64     `json:"DemandID"`
    MealType       string    `json:"MealType"`
    Restaurant     string    `json:"Restaurant"`
    Dish           string    `json:"Dish"`
    Quantity       int       `json:"Quantity"`
    TotalAmount    float64   `json:"TotalAmount"`
    BuyerID        int64     `json:"BuyerID"`
    DeliveryLoc    string    `json:"DeliveryLoc"`
    ServiceCharge  float64   `json:"ServiceCharge"`
    ExpectedTime   string    `json:"ExpectedTime"`
}

func meal_request(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	var mealRequests []MealRequest
    rows, err := db.Query("SELECT num, type, canteen, food, sum, cost, ID, location, fee, time FROM request WHERE time > DATE_ADD(NOW(), INTERVAL 1 HOUR)")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()
    // 遍历结果并填充mealRequests
     for rows.Next() {
        var mr MealRequest
        err := rows.Scan(&mr.DemandID, &mr.MealType, &mr.Restaurant, &mr.Dish, &mr.Quantity, &mr.TotalAmount, &mr.BuyerID, &mr.DeliveryLoc, &mr.ServiceCharge, &mr.ExpectedTime)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
		fmt.Println(mr)
		row,err:=db.Query("SELECT card FROM user WHERE ID = ?", mr.BuyerID)
		if err!= nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer row.Close()
		for row.Next() {
			var card int
			err := row.Scan(&card)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			mr.BuyerID = int64(card)
		}
        mealRequests = append(mealRequests, mr)
    }
	responseJSON, err := json.Marshal(mealRequests)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}

type MealService struct {
	DemandID       int64     `json:"DemandID"`
    MealType       string    `json:"MealType"`
    Restaurant     string    `json:"Restaurant"`
    Dish           string    `json:"Dish"`
	Quantity       int       `json:"Quantity"`
    TotalAmount    float64   `json:"TotalAmount"`
    BuyerID        int64     `json:"BuyerID"`
    DeliveryLoc    string    `json:"DeliveryLoc"`
    ServiceCharge  float64   `json:"ServiceCharge"`
    ServiceTime    string    `json:"ServiceTime"`
}

func meal_service(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	var mealServices []MealService
    rows, err := db.Query("SELECT num, type, canteen, food, sum, cost, ID, location, fee, time FROM service WHERE time > DATE_ADD(NOW(), INTERVAL 1 HOUR)")
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    defer rows.Close()

	// 遍历结果并填充mealServices
     for rows.Next() {
        var ms MealService
        err := rows.Scan(&ms.DemandID, &ms.MealType, &ms.Restaurant, &ms.Dish, &ms.Quantity, &ms.TotalAmount, &ms.BuyerID, &ms.DeliveryLoc, &ms.ServiceCharge, &ms.ServiceTime)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
		fmt.Println(ms)
		row,err:=db.Query("SELECT card FROM user WHERE ID = ?", ms.BuyerID)
		if err!= nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer row.Close()
		for row.Next() {
			var card int
			err := row.Scan(&card)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			ms.BuyerID = int64(card)
		}
        mealServices = append(mealServices, ms)
    }
	responseJSON, err := json.Marshal(mealServices)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}

func request_publish(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	maeltype := r.FormValue("mealType")
	canteen := r.FormValue("restaurant")
	food := r.FormValue("dish")
	quantity, _ := strconv.Atoi(r.FormValue("quantity"))
	cost, _ := strconv.ParseFloat(r.FormValue("totalAmount"), 64)
	card, _ := strconv.Atoi(r.FormValue("buyerID"))	
	location := r.FormValue("deliveryLocation")
	fee, _ := strconv.ParseFloat(r.FormValue("serviceFee"), 64)
	time := r.FormValue("expectedTime")
	row,err:=db.Query("SELECT ID FROM user WHERE card = ?", card)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		card = ID
	}
	_,err = db.Exec("INSERT INTO request (type, canteen, food, sum, cost, ID, location, fee, time) VALUES (?,?,?,?,?,?,?,?,?)", maeltype, canteen, food, quantity, cost, card, location, fee, time)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("需求发布成功")
	response := make(map[string]bool)
	response["success"] = true
	responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
	// insert into request table	
}

func service_publish(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	maeltype := r.FormValue("mealType")
	canteen := r.FormValue("restaurant")
	food := r.FormValue("dish")
	quantity, _ := strconv.Atoi(r.FormValue("quantity"))
	cost, _ := strconv.ParseFloat(r.FormValue("totalAmount"), 64)
	card, _ := strconv.Atoi(r.FormValue("buyerID"))
	location := r.FormValue("deliveryLocation")
	fee, _ := strconv.ParseFloat(r.FormValue("serviceFee"), 64)
	time := r.FormValue("expectedTime")
	row,err:=db.Query("SELECT ID FROM user WHERE card = ?", card)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		card = ID
	}
	_,err = db.Exec("INSERT INTO service (type, canteen, food, sum, cost, ID, location, fee, time) VALUES (?,?,?,?,?,?,?,?,?)", maeltype, canteen, food, quantity, cost, card, location, fee, time)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("服务发布成功")
	response := make(map[string]bool)
	response["success"] = true
	responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
	// insert into request table
}

type Order struct {
	OrderID       int     `json:"OrderID"`
    Card1         int     `json:"Card1"`
	DeliveryLoc   string    `json:"DeliveryLoc"`
	Card2         int     `json:"Card2"`
	MealType      string    `json:"MealType"`
    Restaurant    string    `json:"Restaurant"`
    Dish          string    `json:"Dish"`
    Quantity      int       `json:"Quantity"`
    TotalAmount   float64   `json:"TotalAmount"`
    ServiceCharge float64   `json:"ServiceCharge"`
    OrderTime     string    `json:"OrderTime"`
}

func getRequestOrders(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	_,err = db.Exec("CALL delete_expired_orders();")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var RequestOrders []Order
	card1, _ := strconv.Atoi(r.URL.Query().Get("userID"))
	row,err := db.Query("select ID from user where card = ?" , card1)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		card1 = ID
	}
    rows, err := db.Query("SELECT num, location, PID, type, canteen, food, sum, cost, fee, Ctime FROM `order` WHERE BID = ?", card1)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
	defer rows.Close()
	// 遍历结果并填充mealServices
     for rows.Next() {
        var ms Order
        err := rows.Scan(&ms.OrderID, &ms.DeliveryLoc, &ms.Card2, &ms.MealType, &ms.Restaurant, &ms.Dish, &ms.Quantity, &ms.TotalAmount, &ms.ServiceCharge, &ms.OrderTime)
        ms.Card1 = card1
		if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
		fmt.Println(ms)
		row,err:=db.Query("SELECT card FROM user WHERE ID = ?", ms.Card2)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer row.Close()
		for row.Next() {
			var card int
			err := row.Scan(&card)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			ms.Card2 = card
		}
		ms.Card1,_ = strconv.Atoi(r.URL.Query().Get("userID"))
        RequestOrders = append(RequestOrders, ms)
    }
	responseJSON, err := json.Marshal(RequestOrders)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}

func getServiceOrders(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	_,err = db.Exec("CALL delete_expired_orders();")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	var ServiceOrders []Order
	card2, _ := strconv.Atoi(r.URL.Query().Get("userID"))
	row,err := db.Query("select ID from user where card = ?" , card2)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		card2 = ID
	}
	rows, err := db.Query("SELECT num, BID, location, type, canteen, food, sum, cost, fee, Ctime FROM `order` WHERE PID = ?", card2)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
	defer rows.Close()
	// 遍历结果并填充mealServices
    for rows.Next() {
        var ms Order
        err := rows.Scan(&ms.OrderID, &ms.Card1, &ms.DeliveryLoc, &ms.MealType, &ms.Restaurant, &ms.Dish, &ms.Quantity, &ms.TotalAmount, &ms.ServiceCharge, &ms.OrderTime)
		if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
		ms.Card2 = card2
		fmt.Println(ms)
		row,err:=db.Query("SELECT card FROM user WHERE ID = ?", ms.Card1)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer row.Close()
		for row.Next() {
			var card int
			err := row.Scan(&card)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			ms.Card1 = card
		}
		ms.Card2,_ = strconv.Atoi(r.URL.Query().Get("userID"))
        ServiceOrders = append(ServiceOrders, ms)
    }
	responseJSON, err := json.Marshal(ServiceOrders)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}

func order_complaint(w http.ResponseWriter, r *http.Request) {	
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	OrderID, _ := strconv.Atoi(r.FormValue("OrderID"))
	ComplaintType := r.FormValue("ComplaintType")
	ComplaintContent := r.FormValue("ComplaintContent")
	Complained, _ := strconv.Atoi(r.FormValue("Complained"))
	var count int
	response := make(map[string]bool)
	err = db.QueryRow("SELECT COUNT(*) FROM complaint WHERE num = ?", OrderID).Scan(&count)
	if err != nil {
		fmt.Println(err)
		return
	}else{
		if(count > 0){
			fmt.Println("该订单已有投诉")
			response["success"] = false
		}else{
			row,err:=db.Query("SELECT ID FROM user WHERE card = ?", Complained)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			defer row.Close()
			for row.Next() {
				var ID int
				err := row.Scan(&ID)
				if err != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}
				Complained = ID
			}
			_,err = db.Exec("INSERT INTO complaint (num, type, reason, complained) VALUES (?,?,?,?)", OrderID, ComplaintType, ComplaintContent, Complained)
			if err != nil {
				fmt.Println(err)
				return
			}
			fmt.Println("投诉发布成功")
			response["success"] = true
		}
	}
	responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
}

func confirm_order(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	Card1, _ := strconv.Atoi(r.FormValue("Card1"))
	DeliveryLoc := r.FormValue("DeliveryLoc")
	Card2, _ := strconv.Atoi(r.FormValue("Card2"))
	MealType := r.FormValue("MealType")
	Restaurant := r.FormValue("Restaurant")
	Dish := r.FormValue("Dish")
	Quantity, _ := strconv.Atoi(r.FormValue("Quantity"))
	TotalAmount, _ := strconv.ParseFloat(r.FormValue("TotalAmount"), 64)
	ServiceCharge, _ := strconv.ParseFloat(r.FormValue("ServiceCharge"), 64)
	row,err:=db.Query("SELECT ID FROM user WHERE card = ?", Card1)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		Card1 = ID
	}
	row,err=db.Query("SELECT ID FROM user WHERE card = ?", Card2)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer row.Close()
	for row.Next() {
		var ID int
		err := row.Scan(&ID)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		Card2 = ID
	}
	_,err = db.Exec("INSERT INTO `order` (BID, location, PID, type, canteen, food, sum, cost, fee) VALUES (?,?,?,?,?,?,?,?,?)", Card1, DeliveryLoc, Card2, MealType, Restaurant, Dish, Quantity, TotalAmount, ServiceCharge)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("订单确认成功")
	response := make(map[string]bool)
	response["success"] = true
	responseJSON, err := json.Marshal(response)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }
    // 设置Content-Type为application/json，并返回响应
    w.Header().Set("Content-Type", "application/json")
    w.Write(responseJSON)
	if(r.FormValue("RequestID")!= ""){
		RequestID, _ := strconv.Atoi(r.FormValue("RequestID"))
		_,err = db.Exec("DELETE FROM request WHERE num = ?", RequestID)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("需求删除成功")
	}else{
		ServiceID, _ := strconv.Atoi(r.FormValue("ServiceID"))
		_,err = db.Exec("DELETE FROM service WHERE num = ?", ServiceID)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("服务删除成功")
	}
}

type info struct {
	Card       int      `json:"card"`
    Name       string   `json:"name"`
	Academy    string   `json:"academy"`
	Grade      string   `json:"grade"`
	Tel        int      `json:"tel"`
    Password   string   `json:"password"`
	User_num   int      `json:"user_num"`
}

func stu_info(w http.ResponseWriter, r *http.Request) {
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	var info info
	if r.Method == http.MethodGet {
		info.Card, _ = strconv.Atoi(r.URL.Query().Get("card"))
		rows, err := db.Query("SELECT name, academy, grade, tel FROM student WHERE card = ?", info.Card)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		for rows.Next() {
			err := rows.Scan(&info.Name, &info.Academy, &info.Grade, &info.Tel)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			fmt.Println(info)
		}
		rows.Close()
		rows, err = db.Query("SELECT password, ID FROM user WHERE card = ?", info.Card)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()
		for rows.Next() {
			err := rows.Scan(&info.Password, &info.User_num)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}
		responseJSON, err := json.Marshal(info)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 设置Content-Type为application/json，并返回响应
		w.Header().Set("Content-Type", "application/json")
		w.Write(responseJSON)
	}else if(r.Method == http.MethodPost){
		info.Card, _ = strconv.Atoi(r.FormValue("card"))
		info.Name = r.FormValue("name")
		info.Academy = r.FormValue("academy")
		info.Grade = r.FormValue("grade")
		info.Tel, _ = strconv.Atoi(r.FormValue("tel"))
		info.Password = r.FormValue("password")
		_ ,err := db.Exec("update student set name = ?, academy = ?, grade = ?, tel = ? where card = ?", info.Name, info.Academy, info.Grade, info.Tel, info.Card)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		_,err = db.Exec("update user set password = ? where card = ?", info.Password, info.Card)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Println("修改成功")
		response := make(map[string]bool)
		response["success"] = true
		responseJSON, err := json.Marshal(response)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// 设置Content-Type为application/json，并返回响应
		w.Header().Set("Content-Type", "application/json")
		w.Write(responseJSON)
	}			
}

func admin_login(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	AdminID,_ := strconv.Atoi(r.FormValue("ID"))
	Password := r.FormValue("password")
	var count int
	response := make(map[string]bool)
	err = db.QueryRow("SELECT COUNT(*) FROM administrator WHERE ID = ? AND password = ?", AdminID, Password).Scan(&count)
	if err != nil {
		fmt.Println(err)
		return
	}
	if(count > 0){
		fmt.Println("登录成功")
		
		response["success"] = true
	}else{
		fmt.Println("登录失败")
		response["success"] = false
	}
	responseJSON, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 设置Content-Type为application/json，并返回响应
	w.Header().Set("Content-Type", "application/json")
	w.Write(responseJSON)
}

type Complaint struct {
	ComplaintID    int      `json:"ComplaintID"`
	OrderID        int      `json:"OrderID"`
	ComplaintType  string   `json:"Type"`
	ComplaintReason string   `json:"reason"`
	ComplaintContent string   `json:"content"`
	Complained     int      `json:"complained"`
	
}

func get_complaints(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	var complaints []Complaint
	rows, err := db.Query("SELECT ID, num, type, reason, COALESCE(content, '尚未填写'), complained FROM complaint")
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()
	// 遍历结果并填充complaints
	for rows.Next() {
		var c Complaint
		err := rows.Scan(&c.ComplaintID,&c.OrderID, &c.ComplaintType,&c.ComplaintReason, &c.ComplaintContent, &c.Complained)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		complaints = append(complaints, c)
	}
	responseJSON, err := json.Marshal(complaints)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 设置Content-Type为application/json，并返回响应
	w.Header().Set("Content-Type", "application/json")
	w.Write(responseJSON)
}

func deal_complaint(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	ComplaintID, _ := strconv.Atoi(r.FormValue("ID"))
	DealContent := r.FormValue("ComplaintContent")
	var count int
	response := make(map[string]bool)
	err = db.QueryRow("SELECT COUNT(*) FROM complaint WHERE ID = ?", ComplaintID).Scan(&count)
	if err != nil {
		fmt.Println(err)
		return
	}
	if(count > 0){
		_,err = db.Exec("UPDATE complaint SET content = ? WHERE ID = ?", DealContent, ComplaintID)
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println("投诉处理成功")
		response["success"] = true
	}else{
		fmt.Println("投诉处理失败")
		response["success"] = false
	}
	responseJSON, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 设置Content-Type为application/json，并返回响应
	w.Header().Set("Content-Type", "application/json")
	w.Write(responseJSON)
}

func pull_black(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}
	db, err := Connection()
	if err != nil {
		fmt.Println(err)	
		return	
	}
	defer db.Close()
	ID, _ := strconv.Atoi(r.FormValue("ID"))
	response := make(map[string]bool)
	_, err = db.Exec("update user set type = 2 where ID = ?", ID)
	if err != nil {
		fmt.Println(err)
		return
	}
	_, err =db.Exec("INSERT INTO credit_loss (ID) VALUES (?)", ID)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("拉黑成功")
	response["success"] = true
	responseJSON, err := json.Marshal(response)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	// 设置Content-Type为application/json，并返回响应
	w.Header().Set("Content-Type", "application/json")
	w.Write(responseJSON)
}